<?php

declare(strict_types=1);

namespace app\admin\controller\v1;

use app\common\Backend;
use app\common\model\Customer;
use app\common\model\Order;
use app\common\model\PublicStatus;
use app\common\model\User as ModelUser;
use general\Random;
use Exception;
use think\facade\Db;
use Throwable;
use think\db\exception\PDOException;
use think\exception\ValidateException;

class User extends Backend
{
    protected $withJoinTable = [];
    // 排除字段
    protected $preExcludeFields = ['last_login_time', 'login_failure', 'password', 'salt'];

    protected $quickSearchField = ['username', 'nickname', 'id'];
    /**
     * @var 
     */
    protected $model;
    protected $user_withdrawal;
    public function initialize(): void
    {
        parent::initialize();
        $this->model = new ModelUser();
    }

    /**
     * 查看
     * @throws Throwable
     */
    public function index(): void
    {

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->field($this->indexField)
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => '',
        ]);
    }

    public function userStatistics(): void
    {
        list($where, $alias, $limit, $order) = $this->queryBuilder();
        //普通用户
        $user_count = $this->model->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)->where($where)->where('status', PublicStatus::PUBLIC_STATUS_ONE)->where(['user_type' => PublicStatus::USER_TYPE_ZERO])->count();
        //vip统计
        $user_vip_count = $this->model->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)->where($where)->where('status', PublicStatus::PUBLIC_STATUS_ONE)->where(['user_type' => PublicStatus::USER_TYPE_ONE])->count();
        //全站vip
        $user_sup_vip_count = $this->model->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)->where($where)->where('status', PublicStatus::PUBLIC_STATUS_ONE)->where('user_type', PublicStatus::USER_TYPE_TWO)->count();
        //当天用户新增统计
        $usre_day_insert_count = $this->model->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)->where($where)->where('status', PublicStatus::PUBLIC_STATUS_ONE)->whereDay('create_time')->count();
        $this->success('', [
            'user_count'   => $user_count, //普通用户
            'user_vip_count'  => $user_vip_count, //vip统计
            'user_sup_vip_count'  => $user_sup_vip_count, //全站vip
            'usre_day_insert_count'  => $usre_day_insert_count, //当天用户新增统计
        ]);
    }

    public function add()
    {
        if ($this->request->isPost()) {
            $data = $this->request->post();
            $password = $this->request->post('password','YM123456');
            if (!$data) {
                $this->error(__('Parameter %s can not be empty', ['']));
            }
            /**
             * 由于有密码字段-对方法进行重写
             * 数据验证
             */
            if ($this->modelValidate) {
                try {
                    $validate = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                    $validate = new $validate;
                    $validate->scene('add')->check($data);
                } catch (Throwable $e) {
                    $this->error($e->getMessage());
                }
            }
            $salt   = Random::build('alnum', 16);
            $passwd = encrypt_password($password, $salt);
    
            if(intval($data['user_type']) > 0){
                $data['recharge_time'] = date('Y-m-d',time());
            }
            $data['username'] = 'YM'.date('Ymd',time()). ($this->model->getMaxId() + 1); //用户编号
            $data['label_id'] = Random::build('numeric', 9); //用户编号
            if (empty($data['auth_code'])) {
                $data['auth_code'] = Random::build('alnum', 12);  //授权码
            }

            $customer_id = intval($data['customer_id']);
            $data   = $this->excludeFields($data);
            $result = false;
            Db::startTrans();
            try {
                $data['salt']     = $salt;
                $data['password'] = $passwd;

                $result = $this->model->save($data);
                if($customer_id !== PublicStatus::PUBLIC_STATUS_ZERO){
                    $row = Customer::where('id', $customer_id)->find();
                    if (!$row) {
                        $this->error('未找到当前申请用户');
                    }
                    $row->status = PublicStatus::PUBLIC_STATUS_ONE;
                    $row->user_id = $this->model->id;
                    $row->save();
                }
                Db::commit();
            } catch (ValidateException | Exception | PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($result !== false) {
                $this->success(__('Added successfully'));
            } else {
                $this->error(__('No rows were added'));
            }
        }

        $this->error(__('Parameter error'));
    }

    public function edit($id = null): void
    {
        $row = $this->model->find($id);
        if (!$row) {
            $this->error(__('Record not found'));
        }

        if ($this->request->isPost()) {
            $data = $this->request->post();
            if (!$data) {
                $this->error(('Parameter %s can not be empty'));
            }
            $password = $this->request->post('password', 'YM123456');
            $user_type = $this->request->post('user_type',0);
            $recharge_time = $this->request->post('recharge_time','');
            if ($password) {
                $this->model->resetPassword($id, $password);
            }
            if(intval($user_type) > 0 && !$recharge_time){
                $data['recharge_time'] = date('Y-m-d',time());
            }
            parent::edit();
        }

        unset($row->salt);
        $row->password = '';
        $this->success('', [
            'row' => $row
        ]);
    }

    /**
     * 重写select
     */
    public function select()
    {
        $this->request->filter(['strip_tags', 'trim']);

        list($where, $alias, $limit, $order) = $this->queryBuilder();
        $res = $this->model
            ->withJoin($this->withJoinTable, $this->withJoinType)
            ->alias($alias)
            ->where($where)
            ->order($order)
            ->paginate($limit);

        foreach ($res as $re) {
            $re->nickname_text = $re->username . '(ID:' . $re->id . ')';
        }

        $this->success('', [
            'list'   => $res->items(),
            'total'  => $res->total(),
            'remark' => '',
        ]);
    }

    public function del(array $ids = []): void
    {
        if (!$this->request->isDelete() || !$ids) {
            $this->error(('Parameter error'));
        }
        $where             = [];
        $dataLimitAdminIds = $this->getDataLimitAdminIds();
        if ($dataLimitAdminIds) {
            $where[] = [$this->dataLimitField, 'in', $dataLimitAdminIds];
        }

        $pk      = $this->model->getPk();
        $where[] = [$pk, 'in', $ids];

        $count = 0;
        $data  = $this->model->where($where)->select();
        $this->model->startTrans();
        try {
            foreach ($data as $v) {
                $count += $v->delete(true);
            }
            $this->model->commit();
        } catch (Throwable $e) {
            $this->model->rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success(('Deleted successfully'));
        } else {
            $this->error(('No rows were deleted'));
        }
    }
}
